<?php
class admin_model_user_access extends model
{

	public function login($username, $password)
	{
		$session = bone::get_session();
		$ip = $_SERVER["REMOTE_ADDR"];
		$times = $session->get( $ip );
		if( !$times ) $times=0;
		$times++;
		if($times>10)
		{
			$this->set_error('系统检测到您的登陆行为异常, 限制登陆!');
			return false;
		}
		$session->set( $ip, $times );


		$table_admin_log = bone::get_admin_table('user', 'admin_log');
		$table_admin_log->username = $username;
		$table_admin_log->ip = $ip;
        $table_admin_log->time = time();
		
		$db = bone::get_db();
		$user = $db->get_obj( 'SELECT * FROM `bone_user` WHERE `username`=\''.$username.'\'' );

		$result = false;
		
		if($user)
		{
			if($user->is_admin==0)
			{
			    $table_admin_log->description = '该用户没有登陆后台权限';
				$this->set_error('该用户没有登陆后台权限');
			}
			else
			{
				if( $user->password == md5($password.'Mr Bone') )
				{
					if($user->block==1)
					{
					    $table_admin_log->description = '该用户账号被屏蔽';
						$this->set_error('您的账号被屏蔽， 请和管理员联系');
					}
                    else
                    {
    					$session->clear( $ip );
    					$user = bone::get_user( $user->id );
    					$session->set('admin', $user );
    					
    					$table_admin_log->success = 1;
    					$table_admin_log->description = '登陆成功';

    					$db->execute( 'UPDATE `bone_user` SET `last_visit_time`='.time().' WHERE `id`='.$user->id );
    					$result = $user;
                    }
				}
				else
				{
				    $table_admin_log->description = '密码错误';
					$this->set_error('密码错误');
				}
			}
		}
		else
		{
		    $table_admin_log->description = '用户名不存在';
			$this->set_error('用户名不存在');
		}
		$table_admin_log->save();
		return $result;
	}

	// 退出
	public function logout()
	{
		$session = bone::get_session();
		$session->clear('admin');
		return true;
	}

}
?>